<?php
require_once(SITE_ROOT . 'class/db/DB.class.php');
require_once(SITE_ROOT . 'class/bean/Alliance.class.php');

class DBAlliance {
	
	public function getAlliances($orderby = null) {
		$db = new DB();
		$connection = $db->connect();
		
		if ($orderby == null) {
			$select = "SELECT `alliance#`, `name`, `update` FROM `talliance` ORDER BY `name`";
		}
		else $select = "SELECT `alliance#`, `name`, `update` FROM `talliance` ORDER BY `name`";
		
		if ($stmt = $connection->prepare($select)) {
			$stmt->execute();
			
			$stmt->bindColumn(1, $allianceID);
			$stmt->bindColumn(2, $name);
			$stmt->bindColumn(3, $update);
			
			$alliances = new ArrayObject();
			
			while ($stmt->fetch()) {
				$alliance = new Alliance($allianceID, $name, strtotime($update));
				$alliances->append($alliance);
			}
						
			return $alliances;
		}
	}
	
	public function getAllianceByID($id) {
		$db = new DB();
		$connection = $db->connect();
		
		$select = "SELECT `alliance#`, `name`, `update` FROM `talliance` WHERE `alliance#` = ?";
		
		if ($stmt = $connection->prepare($select)) {
			$stmt->execute(array($id));
			
			$stmt->bindColumn(1, $allianceID);
			$stmt->bindColumn(2, $name);
			$stmt->bindColumn(3, $update);
			
			$alliance = null;
			
			while ($stmt->fetch()) {
				$alliance = new Alliance($allianceID, $name, strtotime($update));
			}
			
			return $alliance;
		}
	}
	
	public function saveAlliance($alliance) {
		$db = new DB();
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('INSERT INTO `talliance` (`alliance#`, `name`, `update`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `name`=VALUES(`name`), `update`=VALUES(`update`)')) {
			$allianceID = $alliance->getAllianceID();
			$name = $alliance->getName();
			$update = date('Y-m-d H:i:s', $alliance->getUpdate());
			
			$stmt->execute(array($allianceID, $name, $update));
		}
	}
	
	public function deleteAlliance($alliance) {
		$db = new DB();
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare("DELETE FROM `talliance` WHERE `alliance#` = ?")) {
			$allianceID = $alliance->getAllianceID();
			
			$stmt->execute(array($allianceID));
		}
	}
		
}

?>